package org.l.qiao.base;

import org.apache.log4j.Logger;
import org.l.qiao.annotation.Key;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 严秋旺 on 2015/6/14.
 */
public class LDate implements LType {
    public static final Logger LOGGER = Logger.getLogger(LDate.class);

    @Override
    public int getLType() {
        return LTYPE_DATE;
    }

    @Override
    public Object parse(Key key, String value) {
        Date date = null;
        String format = key.format();
        DateFormat dateFormat = new SimpleDateFormat(format);

        try {
            date = dateFormat.parse(value);
        } catch (ParseException e) {
            LOGGER.debug("日期转换异常[" + value + "]：" + e);
        }

        return date;
    }

    @Override
    public Object parse(String value) {
        Date date = null;
        String format = "yyyy-MM-dd HH:mm:ss";
        DateFormat dateFormat = new SimpleDateFormat(format);

        try {
            date = dateFormat.parse(value);
        } catch (ParseException e) {
            LOGGER.debug("日期转换异常[" + value + "]：" + e);
        }

        return date;
    }

    @Override
    public String toString(Object object) {

        if (object!=null && object instanceof Date) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return dateFormat.format((Date)object);
        }

        return String.valueOf(object);
    }
}
